const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// 自适应屏幕大小
function resizeCanvas() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
}

// 生成随机数
function random(min, max) {
  return Math.random() * (max - min) + min;
}

// Point类
class Point {
  constructor(x, y, radius, imageSrc) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.image = new Image();
    this.image.src = imageSrc;
    this.velocity = {
      x: random(-5, 5),
      y: random(-5, 5)
    };
  }

  // 绘制
  draw() {
    ctx.drawImage(this.image, this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2);
  }

  // 移动
  move() {
    this.x += this.velocity.x;
    this.y += this.velocity.y;

    // 边界检测
    if (this.x - this.radius < 0 || this.x + this.radius > canvas.width) {
      this.velocity.x = -this.velocity.x;
    }
    if (this.y - this.radius < 0 || this.y + this.radius > canvas.height) {
      this.velocity.y = -this.velocity.y;
    }
  }
}

let point;

// 初始化
function init(x, y) {
  point = new Point(x, y, 100, 'women.jpg');
  
  point.image.onload = function() {
    // 图片加载完成后进行绘制
    animate();
  }
}

// 绘制网球场
function drawTennisCourt() {
  // 绘制外框
  ctx.beginPath();
  ctx.rect(canvas.width / 3, canvas.height / 8, canvas.width / 3, canvas.height * 3 / 4);
  ctx.lineWidth = 2;
  ctx.stroke();

  // 绘制中线
  ctx.beginPath();
  ctx.moveTo(canvas.width / 2, canvas.height / 8);
  ctx.lineTo(canvas.width / 2, canvas.height * 7 / 8);
  ctx.stroke();

  // 绘制发球区
  ctx.beginPath();
  ctx.rect(canvas.width / 3, canvas.height / 4, canvas.width / 3, canvas.height / 2);
  ctx.stroke();

  // 绘制发球线
  ctx.beginPath();
  ctx.moveTo(canvas.width / 3, canvas.height / 2);
  ctx.lineTo(canvas.width * 2 / 3, canvas.height / 2);
  ctx.stroke();
}

// 动画循
function animate() {
  requestAnimationFrame(animate);

  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 重新绘制网球场
  drawTennisCourt();

  // 绘制运动的点
  point.draw();

  // 移动点
  point.move();
}

// 鼠标点击事件
canvas.addEventListener('click', function(event) {
  init(event.clientX, event.clientY);
});

// 监听窗口大小变化
window.addEventListener('resize', function() {
  resizeCanvas();
});

// 初始化
resizeCanvas();
drawTennisCourt();
init(canvas.width / 2, canvas.height / 2);
animate();
